package org.library.factory;

import org.library.controller.BookController;
import org.library.controller.TokenController;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;

import java.text.Annotation;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 控制器工厂
 *
 * @author Chen
 * @since 2023/6/13 14:52
 */

@Configuration
public class ControllerFactory {

    private final ConcurrentMap<Class<?>, Object> controllerMap = new ConcurrentHashMap<>();

    private final BeanFactory beanFactory;

    public ControllerFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
        init();
    }

    public <T> T getController(Class<T> clazz) {
        return (T) controllerMap.computeIfAbsent(clazz, k -> {
            Object o = beanFactory.getBean(clazz);
            controllerMap.put(k, o);
            return o;
        });
    }

    private void init() {
        controllerMap.put(TokenController.class, beanFactory.getBean(TokenController.class));
        controllerMap.put(BookController.class, beanFactory.getBean(BookController.class));
    }
}
